//
//  ForumThreeViewController.m
//  一键车讯
//
//  Created by Rabbit on 14-10-31.
//  Copyright (c) 2014年 lanou.3g.com. All rights reserved.
//

#import "ForumThreeViewController.h"
#import "ForumThree.h"
#import "ForumThreeCell.h"
#import "NetHandler.h"
#import "WebViewController.h"
#import "MJRefresh.h"
#import "ForumArchiver.h"

@interface ForumThreeViewController ()<UITableViewDataSource, UITableViewDelegate>
// 论坛三级页面（车系-品牌-型号-对应的帖子）
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, assign) int countx;
@property (nonatomic, retain) NSString *forumThreeStr;
@property (nonatomic, retain) NSString *rightImageName;

@end

@implementation ForumThreeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.arr = [NSMutableArray array];
        
    }
    return self;
}

// 内存管理
- (void)dealloc
{
    [_arr release];
    [_tableView release];
    [super dealloc];
}

- (void)startData
{
    // 解析论坛三级页面的数据
    NSString *str1 = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/bbs/newForums/%@", self.number];
    self.forumThreeStr = self.number;
    NSString *str2 = @"?pageNo=1&pageSize=19&orderby=replyat";
    NSString *str = [str1 stringByAppendingString:str2];
    
    [NetHandler networkWithURL:str completion:^(id result) {
        
        NSMutableArray *dicArray = [result objectForKey:@"topicList"];
        for (NSDictionary *dic in dicArray) {
            
            ForumThree *forumTh = [[ForumThree alloc] initWithDictionary:dic];
            [self.arr addObject:forumTh];
        }
        [self setupRefresh];
        [self.tableView reloadData];
    }];
}

- (void)setupViews
{
    self.tableView = [[UITableView alloc] init];
    self.tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:self.tableView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 设置标题
    self.title = self.pageTitle;

    //加载数据和视图
    [self startData];
    [self setupViews];
    
    // 论坛中添加我的主页功能，选择时候，写入本地输入库
    // 首先判断当前的论坛时候已经保存，如果是，图标变为实色
    
    // 先反归档
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentPath = [path lastObject];
    
    NSString *forumPath = [documentPath stringByAppendingString:@"/forumArchiver.aaa"];
    
    ForumArchiver *arch = [NSKeyedUnarchiver unarchiveObjectWithFile:forumPath];
    
    if ([self.title isEqualToString:arch.archiverTitle ]) {
     
        self.rightImageName = @"shouye2.png";
    } else {
        self.rightImageName = @"shouye1.png";
    }
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:self.rightImageName] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClicked:)] autorelease];
    
    // 本地存储，将名字传到最近访问的本地数组中
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *document1 = [pathArr lastObject];
    NSString *strPath1 = [document1 stringByAppendingString:@"/arr.xml"];
    NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:strPath1];
    
    if (arr.count == 0) {
        
        NSMutableArray *arr1 = [NSMutableArray array];
        [arr1 writeToFile:strPath1 atomically:YES];
    }
    
    [arr addObject:self.pageTitle];
    
    NSArray *reverseedArrar = [[arr reverseObjectEnumerator] allObjects];
    
    NSMutableArray *array1 = [NSMutableArray arrayWithArray:reverseedArrar];
    

    while (array1.count > 4) {
        [array1 removeObjectAtIndex:4];
    }
    
    [array1 writeToFile:strPath1 atomically:YES];

}

// 点击房子图标之后 ，进行归档操作。
- (void)rightBarButtonItemClicked:(UIBarButtonItem *)barbutton
{
    // 建立沙盒
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentPath = [path lastObject];
    
    NSString *forumPath = [documentPath stringByAppendingString:@"/forumArchiver.aaa"];
    
    ForumArchiver *arch = [[ForumArchiver alloc] init];
    
    if (self.navigationItem.rightBarButtonItem.image == [UIImage imageNamed:@"shouye1.png"]) {
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"shouye2.png"];
        
        // 论坛的界面ID和title归档
        
        arch.archiverTitle = self.pageTitle;
        arch.archiverID = self.number;
        
        // 归档
        [NSKeyedArchiver archiveRootObject:arch toFile:forumPath];
        
    } else if (self.navigationItem.rightBarButtonItem.image == [UIImage imageNamed:@"shouye2.png"]){
        
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"shouye1.png"];
        
        // 论坛的界面和title清空归档
        
        arch.archiverTitle = nil;
        arch.archiverID = nil;
        
        // 归档
        [NSKeyedArchiver archiveRootObject:arch toFile:forumPath];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.arr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"three";
    ForumThreeCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[ForumThreeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
    }
    ForumThree *forum = [self.arr objectAtIndex:indexPath.row];
    cell.titleLabel.text = forum.title;
    // 判断如果flag的值是空，就将picLabel的背景颜色设置为透明
    // 如果flag的值不是空，就将picLabel的背景颜色设置为蓝色
    if (forum.flag == nil) {
        cell.picLabel.backgroundColor = [UIColor clearColor];
    } else {
        cell.picLabel.backgroundColor = [UIColor blueColor];
    }
    cell.picLabel.text = forum.flag;
    return cell;
}

// 推出webViewController页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WebViewController *webView = [[WebViewController alloc] init];
    ForumThree *forumth = [self.arr objectAtIndex:indexPath.row];
    
    webView.forumth = forumth; // 2. 将要传的值给第一步创建的属性
    
    [self.navigationController pushViewController:webView animated:YES];
    
}

// 下拉刷新，上拉加载
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.tableView footerEndRefreshing];
    //
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
//    self.tableView.headerPullToRefreshText = @"准备刷新...";
    self.tableView.headerReleaseToRefreshText = @"松开即可刷新...";
    self.tableView.headerRefreshingText = @"正在刷新...";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"加载中";
    
    self.countx = 2;

}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.tableView reloadData];
        
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}

- (void)footerRereshing
{
    //_dataSource = [[NSMutableArray alloc]init];
    
    //    self.countx += 1;
    NSString *str1 = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/bbs/newForums/%@", self.number];
    
    NSString *str2 = [NSString stringWithFormat:@"?pageNo=%d&pageSize=19&orderby=replyat", self.countx];
    NSString *str = [str1 stringByAppendingString:str2];
    [NetHandler networkWithURL:str completion:^(id result) {
        NSMutableArray *dicArray = [result objectForKey:@"topicList"];
        for (NSDictionary *dic in dicArray) {
            ForumThree *forumTh = [[ForumThree alloc] initWithDictionary:dic];
            [self.arr addObject:forumTh];
        }
        [self.tableView reloadData];
    }];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView footerEndRefreshing];
        _countx += 1;

    });
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
